<script setup>
import {ref, reactive, defineEmits, defineProps, watch, onMounted} from "vue";
import {ElMessage} from "element-plus"
import {add} from "@/api/llm"


const addModelDom = ref()

const formData = ref({
  name: "",
  modelType: null,
  baseUrl: "",
  apiKey: "",
  token: "",
  factory: ""
})

const props = defineProps({
  modelValue: {
    type: Boolean,
    required: true
  },
  factory: {
    type: String,
    required: true
  }
})
const dialogVisible = ref(false)

watch(props, (newValue, oldValue) => {
  dialogVisible.value = newValue.modelValue
  formData.value = {
    name: "",
    modelType: null,
    baseUrl: "",
    apiKey: "",
    token: "",
    factory: ""
  }
});

const emits = defineEmits(['update:modelValue'])

const handleClose = (done) => {
  done()
}

const close = () => {
  emits("update:modelValue", false)
}

const rules = {
  modelType: [{required: true, message: '请选择模型类型', trigger: 'change'}],
  name: [{required: true, message: '请输入模型名称', trigger: 'blur'}],
  baseUrl: [{required: true, message: '请输入基础URL', trigger: 'blur'}],
}

// 测试方法
const onSubmit = () => {
  // 开始校验
  addModelDom.value.validate(valid => {
    if(valid) {
      formData.value.factory = props.factory
      add(formData.value).then(res => {
        ElMessage.success("保存成功")
        console.log(res);
        close()
        addModelDom.value.resetFields()
      })
    } else {
      ElMessage.error("数据输入有误，请重新输入")
    }
  })
}

const modelTypeList = [
  {name: "chat",value: "1"},
  {name: "embedding",value: "2"},
  {name: "rerank",value: "3"},
  {name: "img2text",value: "4"}
]

</script>

<template>
  <el-dialog
      v-model="dialogVisible"
      title="新增模型"
      width="500"
      :before-close="handleClose">
    <el-form ref="addModelDom" :model="formData" :rules="rules" label-width="120px" label-position="top">
      <el-form-item label="模型类型" prop="modelType">
        <el-select placeholder="请选择" v-model="formData.modelType">
          <el-option v-for="el in modelTypeList" :key="el.value" :value="el.name" :label="el.name"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="模型名称" prop="name">
        <el-input placeholder="请输入" v-model="formData.name"></el-input>
      </el-form-item>
      <el-form-item label="基础URL" prop="baseUrl">
        <el-input placeholder="请输入" v-model="formData.baseUrl"></el-input>
      </el-form-item>
      <el-form-item label="API_Key">
        <el-input placeholder="请输入" v-model="formData.apiKey"></el-input>
      </el-form-item>
      <el-form-item label="最大Token数">
        <el-input placeholder="请输入" v-model="formData.token"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="onSubmit">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>

</style>